package com.simpleframe.persistence.hibernate;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;

import com.simpleframe.exception.SimpleframeException;
import com.simpleframe.util.DateUtil;
import com.simpleframe.util.ReflectUtil;
import com.simpleframe.util.Utils;

/**
 * 列表帮助类
 * @author 刘甘露
 *
 */
public class Searcher {

	private int pageNo;
	private int pageSize;
	private Date startDate;
	private Date endDate;
	private String order;
	private Class<?> clazz;
	
	private Map<String,Object> values = null;
	
	private Searcher(){
		
	}
	
	public static Searcher create(){
		return new Searcher();
	}	
	
	public Finder createFinder(Class<?> clazz){
		Finder finder = Finder.create(clazz);
		
		finder.setPageNo(pageNo);
		finder.setPageSize(pageSize);
		finder.addPageOrder(order);
		this.clazz = clazz;
		
		System.out.println("pageNo:"+pageNo);
		System.out.println("pageSize:"+pageSize);
		System.out.println("pageOrder:"+order);
		
		return finder;
	}
	
	public Object getValue(String name){
		if(values==null){
			return null;
		}
		//验证字段
		Field field = ReflectUtil.getField(clazz, name);
		if(field==null){
			throw new SimpleframeException("需要执行搜索的字段不存在");
		}
		String value = (String)values.get(name);
		if("".equals(value.trim())){
			return null;
		}
		
		Object result = null;
		if(field.getType()==String.class){
			if(value==null || "".equals((String)value)){
				return null;
			}
		}
		if(field.getType()==Integer.class){
			result = Integer.valueOf(value);
			if(result==null){
				return null;
			}
		}
		if(field.getType()==Date.class){
			result = DateUtil.get(value, "yyyy-MM-dd HH:mm:ss");
			if(result==null){
				return null;
			}
		}
		System.out.println("value:"+value);
		return value;
	}
	
	public void put(String name, Object value){
		if(values==null){
			values = new HashMap<String, Object>();
		}
		values.put(name, value);
	}
	
	public Object get(String name) {
		if(values == null) return null;
		return values.get(name);
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}
	
	
}
